package cc.eddic.pratice.programmingparadigms.exam.impl;

import cc.eddic.pratice.programmingparadigms.exam.Model.AnswerModel;
import cc.eddic.pratice.programmingparadigms.exam.QuestionBankService;
import cc.eddic.pratice.programmingparadigms.exam.QuestionType;
import cc.eddic.pratice.programmingparadigms.exam.domain.Category;
import cc.eddic.pratice.programmingparadigms.exam.domain.Option;
import cc.eddic.pratice.programmingparadigms.exam.domain.Question;
import cc.eddic.pratice.programmingparadigms.exam.domain.SubCategory;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;

@Slf4j
public class QuestionBankServiceHrjImpl extends QuestionBankServiceImpl implements QuestionBankService {
    @Override
    public List<Question> importQuestions(String questionTextFile) {
        String file = getQuestionFileContent();
        List<Question> questionList = new ArrayList<>();

        String[] line = file.split("\n");
        for (int i = 0; i < line.length; i++) {

            if (line[i].equals("")) {
                continue;
            }

            int index = line[i].indexOf('、');
            String head = line[i].substring(0, index);
            if (Character.isDigit(head.charAt(0))) {
                String description = line[i].substring(index + 1);
                Question q = new Question(Integer.parseInt(head), description, QuestionType.SINGLE_CHOICE);
                for (int n = 0; n < 4; n++) {
                    i = i + 1;
                    String abcd = line[i].substring(0, index);
                    q.add(new Option(line[i].substring(2), abcd.charAt(0), false));
                }
                questionList.add(q);
            }
        }
        return questionList;
    }

    //之前导入的问题所有选项都设置的是false，在这个方法中，要把每道题的正确答案标记出来
    @Override
    public List<Question> importCorrectAnswers(String correctAnswerTextFile) {
        Map<Integer, Character> correctAnswerMap = readCorrectAnswers2("");
        List<Question> questions = importQuestions("");

        for (Question q : questions) {
            q.getOptions().stream().filter(option -> correctAnswerMap.get(q.getNo()).equals(option.getChoice())).findFirst().orElseThrow(IllegalArgumentException::new).changeToCorrectAnswer();

            //匿名类
//            q.getOptions().stream().filter(new Predicate<Option>() {
//                @Override
//                public boolean test(Option option) {
//                    return correctAnswerMap.get(q.getNo()).equals(option.getChoice());
//                }
//            });
        }
        System.out.println(questions);


//传统方法
//        for (int i = 0; i < questions.size(); i++) {
//            Question question = questions.get(i);
//            List<Option> options = question.getOptions();
//            for (int n = 0; n < options.size(); n++) {
//                if (correctAnswerMap.get(questions.get(i).getNo()).equals(options.get(n).getChoice())) {
//                    options.get(n).changeToCorrectAnswer();
//                    break;
//                }
//            }
//        }
        return questions;
    }


    @Override
    public List<AnswerModel> readCorrectAnswers(String correctAnswerTextFile) {
        List<Character> answerList = new ArrayList<>();
        List<AnswerModel> choiceList = new ArrayList<>();

        String file = getAnswerFileContent();
        String[] line = file.split("\n");
        for (int i = 1; i <= line.length; i = i + 2) {
            String[] answer = line[i].split("\t");

            for (String s : answer) {
                answerList.add(s.charAt(0));
//                log.debug("answerList:" + answerList);
            }

        }
        for (int h = 0; h < answerList.size(); h++) {
            choiceList.add(new AnswerModel(h + 1, answerList.get(h)));
//            log.debug("choiceList:" + choiceList.get(h).getQuestionNo() + choiceList.get(h).getChoice());
        }
        return choiceList;
    }

    @Override
    public Map<Integer, Character> readCorrectAnswers2(String correctAnswerTextFile) {
        Map<Integer, Character> correctAnswerMap = new HashMap<>();
        String file = getAnswerFileContent();
        String[] lines = file.split("\n");

        for (int i = 0; i < lines.length; i = i + 2) {
            String[] nos = lines[i].split("\t");
            String[] answers = lines[i + 1].split("\t");

            for (int k = 0; k < nos.length; k++) {
                correctAnswerMap.put(Integer.parseInt(nos[k]), answers[k].charAt(0));
            }
        }
        return correctAnswerMap;
    }

    @Override
    public List<Question> importCategories(String categoryExcelFile){
        try {
            HashMap<String, String> categoryMap = new HashMap<>();
            categoryMap.put("基础", "软件开发基础");
            categoryMap.put("HTML", "软件开发基础");
            categoryMap.put("SQL", "软件开发基础");
            categoryMap.put("DOS", "软件开发基础");
            categoryMap.put("Linux", "软件开发基础");
            categoryMap.put("数学", "软件开发基础");

            categoryMap.put("Word", "办公软件");
            categoryMap.put("Excel", "办公软件");

            categoryMap.put("代码", "代码");


            FileInputStream file = new FileInputStream(categoryExcelFile);
            Workbook workbook = new XSSFWorkbook(file);

            ArrayList<Question> questionList = (ArrayList<Question>) importCorrectAnswers("");


            Sheet categorySheet = workbook.getSheetAt(0);
            Iterator<Row> rowIterator = categorySheet.rowIterator();

            rowIterator.next();
            Row rowSubCategory = rowIterator.next();

            while(rowIterator.hasNext()) {
                try {
                    Row row = rowIterator.next();
                    CellType cellType = row.getCell(0).getCellType();
                    if (cellType == CellType.STRING) {
                        break;
                    }
                    int no =  (int) row.getCell(0).getNumericCellValue();


                    Iterator<Cell> cellIterator = row.cellIterator();
                    while (cellIterator.hasNext()) {
                        Cell cell = cellIterator.next();
                        if (cell.getNumericCellValue() == 1) {
                            int columnIndex = cell.getColumnIndex();
                            String nameSubCategory = rowSubCategory.getCell(columnIndex).getRichStringCellValue().getString();
                            SubCategory subcategory = new SubCategory(nameSubCategory);
                            subcategory.setCategory(new Category(categoryMap.get(nameSubCategory)));
                            questionList.get(no - 1).setSubCategory(subcategory);
                            break;
                        }
                    }

                }
                catch (NumberFormatException e) {
                    break;
                }
            }

            return questionList;
        }
        catch (FileNotFoundException e) {
            log.error("importCategories FileInputStream FileNotFoundException\n");
        } catch (IOException e) {
            log.error("importCategories XSSFWorkbook IOException\n");
        }

        return null;

    }
}
